package com.zsxb.crm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zsxb.crm.dto.ContractDTO;
import com.zsxb.crm.dto.ContractSaveDTO;
import com.zsxb.crm.exception.BaseException;
import com.zsxb.crm.mapper.ActivityMapper;
import com.zsxb.crm.mapper.ContractMapper;
import com.zsxb.crm.mapper.CourseMapper;
import com.zsxb.crm.pojo.Activity;
import com.zsxb.crm.pojo.Contract;
import com.zsxb.crm.pojo.Course;
import com.zsxb.crm.result.PageResult;
import com.zsxb.crm.service.ContractService;
import com.zsxb.crm.vo.ContractVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class ContractServicelmpl implements ContractService {
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ActivityMapper activityMapper;
    //查询合同
    @Override
    public PageResult list(ContractDTO dto) {
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        Page<Contract> contracts = contractMapper.list(dto);
        return new PageResult(contracts.getTotal(),contracts.getResult(),null);
    }

    @Override
    public void addContract(ContractSaveDTO contractSaveDTO) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractSaveDTO, contract);
        Course course = courseMapper.getById(Long.valueOf(contractSaveDTO.getCourseId()));
        if (course == null){
            throw new BaseException("课程信息异常，请联系管理员", 250);
        }
        Activity activity = activityMapper.getByActivityId(contractSaveDTO.getActivityId());
        if (activity == null){
            throw new BaseException("活动信息异常，请联系管理员", 250);
        }

        // 课程费用
        BigDecimal price = course.getPrice();
        // 折扣
        Integer discount = activity.getDiscount();

        // 封装返回值
        contract.setStatus(activity.getStatus());
        contract.setCoursePrice(Integer.parseInt(price.toString().split("\\.")[0]));
        // 订单金额
        if (discount == 0){
            // 0折原价
            contract.setOrder(price.doubleValue());
        }
        contract.setOrder(price.doubleValue() * discount.doubleValue()/10);
        contract.setDiscountType(activity.getName());
        contract.setFinishTime(LocalDateTime.now());
        // TODO
        contract.setBusinessId(1);
        contract.setDeptId(1);

        contractMapper.addContract(contract);
    }
    //修改合同
    @Override
    public void update(ContractDTO dto) {
        //获取文件上传的文件名

        contractMapper.update(dto);

    }

    @Override
    public ContractVO getById2(Long id) {
        return contractMapper.getById2(id);
    }

    //根据id查询合同
    @Override
    public Contract getById(Long id) {
         return contractMapper.getById(id);
    }
}
